package client;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * simple swing gui for the chat client
 */
public class Gui extends JFrame implements ChatLineListener {

    private static final long serialVersionUID = 1L;
    private static int rowstextarea = 20;
    private static int colstextarea = 60;
    private static int width = 400;
    private static int height = 200;
    protected JTextPane outputTextbox;
    protected JTextField inputField;
    private Client chatClient;

    /**
     * creates layout
     *
     * @param title      title of the window
     * @param chatClient chatClient that is used for sending and receiving messages
     */
    public Gui(String title, Client chatClient) {
        System.out.println("starting gui...");

        outputTextbox = new JTextPane();
        outputTextbox.setEditable(false);
        outputTextbox.setMinimumSize(new Dimension(width, height));
        inputField = new JTextField();
        inputField.addActionListener(getInput());
        outputTextbox.setText(chatClient.getHistory().load(10));
        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);

        layout.setHorizontalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(outputTextbox)
                        .addComponent(inputField))
        );

        // layout.linkSize(SwingConstants.HORIZONTAL, findButton, cancelButton);

        layout.setVerticalGroup(layout.createSequentialGroup()
                .addComponent(outputTextbox)
                .addComponent(inputField));

        // register listener so that we are informed whenever a new chat message
        // is received (observer pattern)
        chatClient.addLineListener(this);

        setTitle(title);
        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.chatClient = chatClient;
    }

    private ActionListener getInput() {
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                chatClient.send((String) inputField.getText());
                inputField.setText("");
            }
        };
    }

    /**
     * this method gets called every time a new message is received (observer
     * pattern)
     */
    public void newChatLine(String line) {
        final StyledDocument doc = outputTextbox.getStyledDocument();
        final Style style = outputTextbox.addStyle("Ich bin der Style!", null);
        final StringBuffer stringBuffer = new StringBuffer();


        final Pattern p = Pattern.compile("\\<(.*?)\\>(.*)\\<\\/(.*?)\\>");
        final Matcher m = p.matcher(line);
        if (m.find(1)) {
            StringBuffer sb = new StringBuffer();
            m.appendReplacement(sb, m.group(2));
            m.appendTail(sb);
            line = sb.toString();
            if (m.group(1).equals("rot")) {
                StyleConstants.setForeground(style, Color.RED);
            } else if (m.group(1).equals("blau")) {
                StyleConstants.setForeground(style, Color.BLUE);
            } else {
                StyleConstants.setForeground(style, Color.BLACK);
            }
        } else {
            StyleConstants.setForeground(style, Color.BLACK);
        }

        try {
            doc.insertString(doc.getLength(), line, style);
        } catch (BadLocationException e) {
        }


    }

}
